package com.example.Dao;

import com.example.JDBCConnection;
import com.example.pojo.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ClassName: StudentDAO
 * Package: com.example.Dao
 * Description:
 *
 * @Author: liu
 * @Create: 2025/5/28 11:34
 * @Version:1.0
 */
public class StudentDAO {
    // 添加学生
    public void addStudent(Student student) {
        String sql = "INSERT INTO student (id, name, password, dormitory_id) VALUES (?, ?, ?, ?)";
        try (Connection conn = JDBCConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, student.getId());
            pstmt.setString(2, student.getName());
            pstmt.setString(3, student.getPassword());
            pstmt.setString(4, student.getDormitoryId());
            pstmt.executeUpdate();
            System.out.println("学生信息添加成功");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("添加失败：" + e.getMessage());
        }
    }

    // 查看所有学生（关联宿舍名称）
    public void listStudents() {
        String sql = "SELECT s.id, s.name, d.name AS dorm_name " +
                "FROM student s LEFT JOIN dormitory d ON s.dormitory_id = d.id";
        try (Connection conn = JDBCConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            System.out.println("学生列表：");
            while (rs.next()) {
                System.out.printf("ID: %s, 姓名: %s, 宿舍: %s%n",
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("dorm_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    // 删除学生
    public void deleteStudent(String studentId) {
        String sql = "DELETE FROM student WHERE id = ?";
        try (Connection conn = JDBCConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, studentId);
            int rows = pstmt.executeUpdate();
            if (rows > 0) {
                System.out.println("学生删除成功");
            } else {
                System.out.println("未找到对应的学生信息，删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
